//
//  XTXGongTool.m
//  xiaotianxin
//
//  Created by XYC on 2019/6/19.
//  Copyright © 2019 XYC. All rights reserved.
//

#import "XTXGongTool.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
#import "XTXNetworkingPageViewController.h"

NSString *const kInitVector0 = @"16-Bytes--String";
size_t const kKeySize0 = kCCKeySizeAES128;

static XTXGongTool *tool = nil;


@interface XTXGongTool ()

@end

@implementation XTXGongTool

+ (void)huoquyonghudetonghuashijian:(NSString *) userID completionHandler:(void (^)(NSString * model))completionHandler
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"user_id"] = userID;

    [XTXNetworking networkingGetUseTonghuaTimedewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            if (completionHandler) {
                completionHandler([NSString stringWithFormat:@"通话:%@", [XTXGongTool shijianHuansuanShiFenMiao:dict[@"calltimetotal"]]]);
            }
        }
    }];
}
+ (NSString *)shijianHuansuanShiFenMiao:(NSString *)shijianChangduString
{
    
    if ([shijianChangduString intValue]<60*60&&[shijianChangduString intValue]>=60) {
        NSString *time = [NSString stringWithFormat:@"%d分%d秒",[shijianChangduString intValue]/60,[shijianChangduString intValue]%60];
        return time;
    }else if ([shijianChangduString intValue]<60) {
        NSString *time = [NSString stringWithFormat:@"%d秒",[shijianChangduString intValue]%60];
        return time;
    }else if ([shijianChangduString intValue]>=60*60){
        NSString *time = [NSString stringWithFormat:@"%d小时%d分",[shijianChangduString intValue]/(60*60),([shijianChangduString intValue]%(60*60)/60)];
        return time;
    }
    
    return nil;
}
+ (void)huoquyonghugetImV2dewangluoqingqiu:(NSString *) userID completionHandler:(void (^)(NSString * model))completionHandler
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"f_user_id"] = userID;
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    [XTXNetworking networkingGetImV2Eveedewangluoqingqiu:canshuMutDict completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            if (completionHandler) {
                completionHandler(dict[@"code"]);
            }
        }
        
    }];
}

+ (void)huoquyonghudegerenxinxiEventClick:(NSString *) userID completionHandler:(void (^)(XTXUserModel * model))completionHandler
{
    
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"id"] = userID;
    [XTXNetworking networkingGetUseInfowangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            
            XTXUserModel *model = [XTXUserModel yy_modelWithDictionary:dict[@"info"]];

            if (completionHandler) {
                completionHandler(model);
            }
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [XTXGongView showTipMsg:dict[@"msg"]];
                [XTXGongTool.GetDangqiaViewController.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
    
}

+ (void)huoquyonghuguanzhuhequxiaoguanzhudeEventClcik:(NSString *) followUserId withGzButton:(UIButton *) gzButton
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    canshuMutDict[@"follow_user_id"] = followUserId;
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    WeakSelf
    [XTXNetworking networkingGuanzhuCancelGuanzhuUsedewangluojiekou:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            [weakSelf huoquyonghuguanxiheguanzhuanniudeEventClick:followUserId withGzButton:gzButton];
        }
        [XTXGongView showTipMsg:dict[@"msg"]];
    }];
    
}

+ (void)huoquyonghuguanxiheguanzhuanniudeEventClick:(NSString *) followUserId withGzButton:(UIButton *)gzButton
{
    NSMutableDictionary *canshuMutDict = [NSMutableDictionary dictionary];
    
    canshuMutDict[@"follow_user_id"] = followUserId;
    canshuMutDict[@"user_id"] = XTXGongTool.share.useMode.id;
    
    [XTXNetworking networkingShifouGuanzhuUsedewangluoqingqiu:canshuMutDict.copy completionHandler:^(NSDictionary * _Nonnull dict) {
        if ([dict[@"code"] isEqualToString:@"1"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [gzButton setImage:[UIImage imageNamed:@"关注-已关注"] forState:UIControlStateNormal];
            });
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [gzButton setImage:[UIImage imageNamed:@"关注-未关注"] forState:UIControlStateNormal];
            });
        }
    }];
}


+ (UIImage *)tongguozhaoxiangjihuoquyizhangtupianEventClick:(UIImage *) oneImg
{
    // No-op if the orientation is already correct
    if  (oneImg .imageOrientation  == UIImageOrientationUp)
        return  oneImg;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform exciteTrans = CGAffineTransformIdentity;
    
    switch  (oneImg .imageOrientation ) {
        case  UIImageOrientationDown :
        case  UIImageOrientationDownMirrored :
            exciteTrans = CGAffineTransformTranslate(exciteTrans, oneImg .size .width , oneImg .size .height );
            exciteTrans = CGAffineTransformRotate(exciteTrans, M_PI);
            break ;
            
        case  UIImageOrientationLeft :
        case  UIImageOrientationLeftMirrored :
            exciteTrans = CGAffineTransformTranslate(exciteTrans, oneImg .size .width ,  0 );
            exciteTrans = CGAffineTransformRotate(exciteTrans, M_PI_2 );
            break ;
            
        case  UIImageOrientationRight :
        case  UIImageOrientationRightMirrored :
            exciteTrans = CGAffineTransformTranslate(exciteTrans,  0 , oneImg .size .height );
            exciteTrans = CGAffineTransformRotate(exciteTrans, -M_PI_2 );
            break ;
        default :
            break ;
    }
    
    switch  (oneImg .imageOrientation ) {
        case  UIImageOrientationUpMirrored :
        case  UIImageOrientationDownMirrored :
            exciteTrans = CGAffineTransformTranslate(exciteTrans, oneImg .size .width ,  0 );
            exciteTrans = CGAffineTransformScale(exciteTrans, - 1 ,  1 );
            break ;
            
        case  UIImageOrientationLeftMirrored :
        case  UIImageOrientationRightMirrored :
            exciteTrans = CGAffineTransformTranslate(exciteTrans, oneImg .size .height ,  0 );
            exciteTrans = CGAffineTransformScale(exciteTrans, - 1 ,  1 );
            break ;
        default :
            break ;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef gloryContext = CGBitmapContextCreate( NULL , oneImg .size .width , oneImg .size .height ,
                                             CGImageGetBitsPerComponent(oneImg .CGImage ),  0 ,
                                             CGImageGetColorSpace(oneImg .CGImage ),
                                             CGImageGetBitmapInfo(oneImg .CGImage ));
    CGContextConcatCTM(gloryContext, exciteTrans);
    switch  (oneImg .imageOrientation ) {
        case  UIImageOrientationLeft :
        case  UIImageOrientationLeftMirrored :
        case  UIImageOrientationRight :
        case  UIImageOrientationRightMirrored :
            // Grr...
            CGContextDrawImage(gloryContext, CGRectMake( 0 , 0 ,oneImg .size .height ,oneImg .size .width ), oneImg .CGImage );
            break ;
            
        default :
            CGContextDrawImage(gloryContext, CGRectMake( 0 , 0 ,oneImg .size .width ,oneImg .size .height ), oneImg .CGImage );
            break ;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg1 = CGBitmapContextCreateImage(gloryContext);
    UIImage  *img1 = [UIImage  imageWithCGImage :cgimg1];
    CGContextRelease(gloryContext);
    CGImageRelease(cgimg1);
    return  img1;
}

+ (NSString *)shijianchushihua:(NSString *) timStr
{
    NSRange inter = {4,2};
    NSString *str = [timStr substringWithRange:inter];
    NSRange inter1 = {6,2};
    NSString *str1 = [timStr substringWithRange:inter1];
    NSRange inter2 = {8,2};
    NSString *str2 = [timStr substringWithRange:inter2];
    NSRange inter3 = {10,2};
    NSString *str3 = [timStr substringWithRange:inter3];
    if (str2.integerValue<=12) {
        NSString *mightStr = [NSString stringWithFormat:@"%@-%@ 上午%@:%@",str,str1,str2,str3];
        return mightStr;
    }else{
        NSString *mightStr = [NSString stringWithFormat:@"%@-%@ 下午%ld:%@",str,str1,str2.integerValue-12,str3];
        return mightStr;
    }
    
}


+ (UIImage *)tongguoxiugaiyansededaoyizhangxindetupianEventClick:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



- (void)dedaoyonghuxinxideClick
{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"useMode"];
    if (data) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        self.useMode = [XTXUserModel yy_modelWithDictionary:dict];
        XTXTool.share.ConsumerModel = [ConsumerModel yy_modelWithDictionary:dict];
    }
    else {
        
    }
}

+ (void)baocungerenwangluqingiqushujuEventClick:(XTXUserModel *)useMode
{
    if (useMode.token.length) {
        [[NSUserDefaults standardUserDefaults] setObject:useMode.token forKey:@"yonghuToken"];
    }
    if (useMode.aeskey.length) {
        [[NSUserDefaults standardUserDefaults] setObject:useMode.aeskey forKey:@"yonghuJiamiKey"];
    }
    if (useMode.birthday.length && ![useMode.birthday rangeOfString:@"/"].length) {
        NSMutableString *tempMutString = useMode.birthday.mutableCopy;
        [tempMutString insertString:@"/" atIndex:4];
        [tempMutString insertString:@"/" atIndex:7];
        useMode.birthday = tempMutString.copy;
    }
    NSData *data = [useMode yy_modelToJSONData];
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"useMode"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}


+ (UIViewController *)GetDangqiaViewController
{
    UIViewController *agreeablyViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (1) {
        
        if ([agreeablyViewController isKindOfClass:[UITabBarController class]]) {
            
            agreeablyViewController = ((UITabBarController *)agreeablyViewController).selectedViewController;
            
        }
        
        if ([agreeablyViewController isKindOfClass:[UINavigationController class]]) {
            
            agreeablyViewController = ((UINavigationController *)agreeablyViewController).visibleViewController;
            
        }
        
        if (agreeablyViewController.presentedViewController) {
            
            agreeablyViewController = agreeablyViewController.presentedViewController;
            
        }
        else{
            
            break;
            
        }
    }
    
    return agreeablyViewController;
}

+ (NSString *)AesJiam:(NSDictionary *)dic key:(NSString *)key
{
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        //NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    NSData *contentData = [mutStr dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = contentData.length;

    char keyPtr[kKeySize0 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    size_t encryptSize = dataLength + kCCBlockSizeAES128;
    void *encryptedBytes = malloc(encryptSize);
    size_t actualOutSize = 0;
    NSData *initVector = [kInitVector0 dataUsingEncoding:NSUTF8StringEncoding];
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kKeySize0,
                                          initVector.bytes,
                                          contentData.bytes,
                                          dataLength,
                                          encryptedBytes,
                                          encryptSize,
                                          &actualOutSize);
    if (cryptStatus == kCCSuccess) {
        // 对加密后的数据进行 base64 编码
        NSData *data= [[[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed] dataUsingEncoding:NSUTF8StringEncoding];
        if (!data || [data length] == 0) {
            return @"";
        }
        NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
        
        [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
            unsigned char *dataBytes = (unsigned char*)bytes;
            for (NSInteger i = 0; i < byteRange.length; i++) {
                NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
                if ([hexStr length] == 2) {
                    [string appendString:hexStr];
                } else {
                    [string appendFormat:@"0%@", hexStr];
                }
            }
        }];
        
        return string;
        
    }
    free(encryptedBytes);
    return nil;
}

+ (instancetype)share
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(tool == nil)
        {
            tool = [[self alloc] init];
        }
    });
    return tool;
}

+ (id)allocWithZone:(NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (tool == nil)
        {
            tool = [super allocWithZone:zone];
            //NSLog(@"allocWithZone");
        }
    });
    return tool;
}

- (id)init
{
    self = [super init];
    if (self != nil)
    {
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

@end
